package org.monitor.command;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.text.ParseException;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import org.apache.log4j.Logger;
import org.monitor.beans.CommandDTO;
import org.monitor.beans.RequestParam;
import org.monitor.common.Common;
import org.monitor.main.MClient;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.matchers.GroupMatcher;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class RegistServerCommand implements Job {

	private static Logger logger = Logger.getLogger(RegistServerCommand.class);
	public void execute(JobExecutionContext context) throws JobExecutionException {
		
		//
		
		
		
		Scheduler scheduler = MClient.getInstance().getScheduler();
		try {
			
			GroupMatcher<JobKey> matcher=GroupMatcher.groupStartsWith("command");
			Set s=scheduler.getJobKeys(matcher);
			for(Iterator<JobKey> iter=s.iterator();iter.hasNext();)
			{
				scheduler.deleteJob(iter.next());
			}
		} catch (SchedulerException e1) {
			// TODO Auto-generated catch block
			logger.error("RegistServerCommand:\t"+ e1.getMessage());
			e1.printStackTrace();
		}

		JobDataMap jmap = context.getMergedJobDataMap();
		Properties conf = (Properties) jmap.get("conf");
		String registerKey = MClient.getKey();
		RequestParam param = Common.makeSign(registerKey);
		param.getParam().put("port", conf.getProperty("client.port"));
		param.setAction("registerService");
		String url = "http://" + conf.getProperty("server.ip") + ":" + conf.getProperty("server.port");
		String config = Common.postData(url, param.getParamsForClent());
		JSONObject jsonObject = JSONObject.parseObject(config);
		JSONObject commonCommand = jsonObject.getJSONObject("common");

	    
		
		for (String category : commonCommand.keySet()) {
			JSONArray jarray = commonCommand.getJSONArray(category);
			for (int i = 0; i < jarray.size(); i++) {
				JSONObject obj = (JSONObject) jarray.get(i);
				CommandDTO dto = new CommandDTO();
				dto.setSection("common");
				dto.setCategory(category);
				dto.setCommand(obj.getString("command"));
				dto.setCron(obj.getString("cron"));
				dto.setDesc(obj.getString("desc"));
				dto.setDuring(obj.getString("during"));
				dto.setEmail(obj.getString("email"));
				dto.setHandle(obj.getString("handler"));
				dto.setKey(obj.getString("key"));
				dto.setAssertFunction(obj.getString("assertfunction"));
				dto.setAssertValue(obj.getString("assertValue"));
				dto.setLine(obj.getIntValue("line"));
				CronTrigger trigger = null;
				try {
					trigger = newTrigger().withIdentity(dto.getKey(),"command"+ dto.getCategory()).withSchedule(cronSchedule(dto.getCron())).build();
				} catch (ParseException e) {
					e.printStackTrace();
				}
				JobBuilder jbuilder = newJob(ExcuteHandleCommand.class).withIdentity(dto.getKey(),"command"+ dto.getCategory() + "-" + dto.getSection());
				JobDataMap context2 = new JobDataMap();
				context2.put("command", dto);
				jbuilder.usingJobData(context2);
				jbuilder.requestRecovery();
				JobDetail job = jbuilder.build();
				try {
					if (scheduler.getJobDetail(job.getKey()) == null) {
						scheduler.scheduleJob(job, trigger);
					} else {
						scheduler.deleteJob(job.getKey());
						scheduler.scheduleJob(job, trigger);
					}
				} catch (SchedulerException e) {
					e.printStackTrace();
				}
			}
		}
		JSONObject privateCommand = jsonObject.getJSONObject("private");
		for (String category : privateCommand.keySet()) {
			JSONArray jarray = privateCommand.getJSONArray(category);
			for (int i = 0; i < jarray.size(); i++) {
				JSONObject obj = (JSONObject) jarray.get(i);
				CommandDTO dto = new CommandDTO();
				dto.setSection("private");
				dto.setCategory(category);
				dto.setCommand(obj.getString("command"));
				dto.setCron(obj.getString("cron"));
				dto.setDesc(obj.getString("desc"));
				dto.setDuring(obj.getString("during"));
				dto.setEmail(obj.getString("email"));
				dto.setHandle(obj.getString("handler"));
				dto.setKey(obj.getString("key"));
				dto.setAssertFunction(obj.getString("assertfunction"));
				dto.setAssertValue(obj.getString("assertValue"));
				dto.setLine(obj.getIntValue("line"));
				CronTrigger trigger = null;
				try {
					trigger = newTrigger().withIdentity(dto.getKey(),"command"+ dto.getCategory()).withSchedule(cronSchedule(dto.getCron())).build();
				} catch (ParseException e) {
					e.printStackTrace();
				}
				JobBuilder jbuilder = newJob(ExcuteHandleCommand.class).withIdentity(dto.getKey(),"command"+ dto.getCategory() + "-" + dto.getSection());
				JobDataMap context2 = new JobDataMap();
				context2.put("command", dto);
				jbuilder.usingJobData(context2);
				jbuilder.requestRecovery();
				JobDetail job = jbuilder.build();
				try {
					if (scheduler.getJobDetail(job.getKey()) == null) {
						scheduler.scheduleJob(job, trigger);
					} else {
						scheduler.deleteJob(job.getKey());
						scheduler.scheduleJob(job, trigger);
					}
				} catch (SchedulerException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
